package com.pdsu.xpf.graduation01.utils;

import com.pdsu.xpf.graduation01.domain.User;
import io.jsonwebtoken.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.UUID;

@Component
public class JwtComponent {

    /**
     *
     * 生成token
     * @param user
     * 用户
     * @param expTime
     * 超时时间
     * @return
     */
    public String makeToken(User user, long expTime){

        //将User信息装入
        JwtBuilder jwtBuilder= Jwts.builder();

        String jwtToken= jwtBuilder
                //头信息
                .setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                //payload 将信息装入
                .claim("username",user.getName())
                .claim("uid",user.getUid())
                .setExpiration(new Date(System.currentTimeMillis()+expTime))
                .setId(UUID.randomUUID().toString())
                //signature
                .signWith(SignatureAlgorithm.HS256,user.getPhone())
                .compact();
        System.out.println(jwtToken);
        //用uid+password作为signature
        //有效时间设置为30天
        //返回token
        return jwtToken;
    }

    /**
     * 检查token
     * @param token
     * 目标token
     * @param user
     * 目标用户
     * @return
     */
    public boolean checkToken(String token, User user){

        JwtParser jwtParser=Jwts.parser();
        try {
            jwtParser.setSigningKey(user.getPhone()).parse(token);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token 解析失败 ，失败原因"+e);
            return false;
        }

        System.out.println("解析成功");
        return true;
    }

    //从token中获取userid
    private int getUserID(String token,String userName){
        JwtParser jwtParser=Jwts.parser();
        Jws<Claims> claimsJws= jwtParser.setSigningKey(userName).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Object obj=claims.get("uid");
        Integer uid= (Integer) obj;
        return uid;
    }
    //从token中获取userid
    private int getTokenUserIDByUserPhone(String token,String phone){
        JwtParser jwtParser=Jwts.parser();
        Jws<Claims> claimsJws= jwtParser.setSigningKey(phone).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Object obj=claims.get("uid");
        Integer uid= (Integer) obj;
        return uid;
    }
    //从token中获取username
    private String getUserName(){
        JwtParser jwtParser=Jwts.parser();

        return "";
    }




}
